<template>
  <div>
    <el-card>
      <template #header>
        <h2>人口查询</h2>
      </template>
      <el-form inline style="margin-left: 300px;">
        <el-form-item label="查询：">
          <el-select v-model="searchWhatis" placeholder="请选择查询方向" filterable>
            <el-option label="户号" value="0" />
            <el-option label="姓名" value="1" />
            <el-option label="身份证号" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left: 25px;">
          <el-input v-model="input" placeholder="请输入查询内容" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button type="default" @click="openAddUser">添加</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" border height="300">
        <el-table-column prop="personId" label="编号" width="100" />
        <el-table-column prop="name" label="姓名" width="150" />
        <el-table-column prop="gender" label="性别" width="100" />
        <el-table-column prop="birthDate" label="出生日期">
          <template #default="scope">
            <el-input v-model="scope.row.birthDate" :disabled="true"
              :value="scope.row.birthDate ? new Date(scope.row.birthDate).toLocaleDateString() : ''" />
          </template>
        </el-table-column>
        <el-table-column prop="idNumber" label="身份证号" width="180" />
        <el-table-column prop="householdNumber" label="家庭户号" />
        <el-table-column prop="phoneNumber" label="电话号码" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="success" size="small" @click="getUser(scope.row)">查看</el-button>
            <el-button type="success" size="small" @click="editUser(scope.row)">编辑</el-button>
            <el-button type="warning" size="small" @click="confirmDeleteUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; justify-content: center;">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
    <!-- 个人信息弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="title" width="1050">
      <el-form :model="populationInfo" :rules="rules" ref="populationInfoForm">
        <el-row>
          <el-col :span="8">
            <el-form-item label="编号" label-width="100" prop="personId">
              <el-input v-model="populationInfo.personId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" label-width="100" prop="name">
              <el-input v-model="populationInfo.name" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" label-width="100" :formatter="genderFormatter" prop="gender">
              <el-select v-model="populationInfo.gender" placeholder="请选择性别" style="width:100%" filterable>
                <el-option label="男" value="1" />
                <el-option label="女" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="出生日期" label-width="100" prop="birthDate">
              <el-date-picker v-model="populationInfo.birthDate" type="date" placeholder="请选择生日" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号" label-width="100" prop="idNumber">
              <el-input v-model="populationInfo.idNumber" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="民族" label-width="100" prop="ethnicity">
              <el-select v-model="populationInfo.ethnicity" placeholder="请选择民族" filterable>
                <el-option v-for="option in ethnicityOptions" :key="option" :label="option" :value="option" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="与户主关系" label-width="100" :formatter="relationToHeadFormatter" prop="relationToHead">
              <el-select v-model="populationInfo.relationToHead" placeholder="请选择关系" style="width:100%" filterable>
                <el-option label="配偶" value="1" />
                <el-option label="子女" value="2" />
                <el-option label="户主" value="3" disabled />
                <el-option label="父母" value="4" />
                <el-option label="其他" value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="婚姻状况" label-width="100" :formatter="maritalStatusFormatter" prop="maritalStatus">
              <el-select v-model="populationInfo.maritalStatus" placeholder="请选择婚姻情况" style="width:100%" filterable>
                <el-option label="未婚" value="1" />
                <el-option label="已婚" value="2" />
                <el-option label="离异" value="3" />
                <el-option label="丧偶" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="教育程度" label-width="100" :formatter="educationLevelFormatter" prop="educationLevel">
              <el-select v-model="populationInfo.educationLevel" placeholder="请选择性别" style="width:100%" filterable>
                <el-option label="学龄前" value="1" />
                <el-option label="小学" value="2" />
                <el-option label="初中" value="3" />
                <el-option label="高中" value="4" />
                <el-option label="本科" value="5" />
                <el-option label="研究生" value="6" />
                <el-option label="其它" value="7" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="职业" label-width="100" prop="occupation">
              <el-input v-model="populationInfo.occupation" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话号码" label-width="100" prop="phoneNumber">
              <el-input v-model="populationInfo.phoneNumber" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="家庭户号" label-width="100" prop="householdNumber">
              <el-input v-model="populationInfo.householdNumber" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否残疾" label-width="100" :formatter="isDisabledFormatter" prop="isDisabled">
              <el-select v-model="populationInfo.isDisabled" placeholder="请选择婚姻情况" style="width:100%" filterable>
                <el-option label="残疾" value="1" />
                <el-option label="不残疾" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="血型" label-width="100" :formatter="bloodTypeFormatter" prop="bloodType">
              <el-select v-model="populationInfo.bloodType" placeholder="请选择婚姻情况" style="width:100%" filterable>
                <el-option label="A" value="1" />
                <el-option label="B" value="2" />
                <el-option label="AB" value="3" />
                <el-option label="O" value="4" />
                <el-option label="其他" value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服兵役状况" label-width="100" :formatter="militaryStatusFormatter" prop="militaryStatus">
              <el-select v-model="populationInfo.militaryStatus" placeholder="请选择婚姻情况" style="width:100%" filterable>
                <el-option label="未服兵役" value="1" />
                <el-option label="现役" value="2" />
                <el-option label="退役" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="8">
            <el-form-item label="户籍住址" label-width="100" prop="registeredAddress">
              <el-input v-model="populationInfo.household.registeredAddress" disabled />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveOrUpdatePopulationInfo">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogFormVisibles" :title="title" width="1050">
      <el-form :model="populationInfo">
        <el-row>
          <el-col :span="8">
            <el-form-item label="编号" label-width="100">
              <el-input v-model="populationInfo.personId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" label-width="100">
              <el-input v-model="populationInfo.name" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" label-width="100" :formatter="genderFormatter">
              <el-select v-model="populationInfo.gender" placeholder="请选择性别" style="width:100%" disabled>
                <el-option label="男" value="1" />
                <el-option label="女" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="出生日期" label-width="100">
              <el-input v-model="populationInfo.birthDate" :disabled="true"
                :value="populationInfo.birthDate ? new Date(populationInfo.birthDate).toLocaleDateString() : ''" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号" label-width="100">
              <el-input v-model="populationInfo.idNumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="民族" label-width="100">
              <el-input v-model="populationInfo.ethnicity" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="与户主关系" label-width="100" :formatter="relationToHeadFormatter">
              <el-select v-model="populationInfo.relationToHead" placeholder="请选择关系" style="width:100%" disabled>
                <el-option label="配偶" value="1" />
                <el-option label="子女" value="2" />
                <el-option label="户主" value="3" />
                <el-option label="父母" value="4" />
                <el-option label="其他" value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="婚姻状况" label-width="100" :formatter="maritalStatusFormatter">
              <el-select v-model="populationInfo.maritalStatus" placeholder="请选择婚姻情况" style="width:100%" disabled>
                <el-option label="未婚" value="1" />
                <el-option label="已婚" value="2" />
                <el-option label="离异" value="3" />
                <el-option label="丧偶" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="教育程度" label-width="100" :formatter="educationLevelFormatter">
              <el-select v-model="populationInfo.educationLevel" placeholder="请选择性别" style="width:100%" disabled>
                <el-option label="学龄前" value="1" />
                <el-option label="小学" value="2" />
                <el-option label="初中" value="3" />
                <el-option label="高中" value="4" />
                <el-option label="本科" value="5" />
                <el-option label="研究生" value="6" />
                <el-option label="其它" value="7" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="职业" label-width="100">
              <el-input v-model="populationInfo.occupation" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话号码" label-width="100">
              <el-input v-model="populationInfo.phoneNumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="家庭户号" label-width="100">
              <el-input v-model="populationInfo.householdNumber" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否残疾" label-width="100" :formatter="isDisabledFormatter" prop="isDisabled">
              <el-select v-model="populationInfo.isDisabled" placeholder="请选择残疾情况" style="width:100%" filterable
                disabled>
                <el-option label="残疾" value="1" />
                <el-option label="不残疾" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="血型" label-width="100" :formatter="bloodTypeFormatter" prop="bloodType">
              <el-select v-model="populationInfo.bloodType" placeholder="请选择血型" style="width:100%" filterable disabled>
                <el-option label="A" value="1" />
                <el-option label="B" value="2" />
                <el-option label="AB" value="3" />
                <el-option label="O" value="4" />
                <el-option label="其他" value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服兵役状况" label-width="100" :formatter="militaryStatusFormatter" prop="militaryStatus">
              <el-select v-model="populationInfo.militaryStatus" placeholder="请选择服兵役情况" style="width:100%" filterable
                disabled>
                <el-option label="未服兵役" value="1" />
                <el-option label="现役" value="2" />
                <el-option label="退役" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="8">
            <el-form-item label="户籍住址" label-width="100" prop="registeredAddress">
              <el-input v-model="populationInfo.household.registeredAddress" disabled />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-form-item label="" label-width="100">
          <el-input v-model="populationInfo.isAlive" style="width: 200px;" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibles = false">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { getPopulationPage, updatePopulation, deletePopulation, addPopulation } from '@/api/population';
import { ElMessage, ElMessageBox } from 'element-plus';

//民族
const ethnicity = ref('');
const ethnicityOptions = [
  '汉族', '蒙古族', '回族', '藏族', '维吾尔族', '苗族', '彝族', '壮族', '满族', '朝鲜族', '侗族', '瑶族', '白族', '土家族', '哈尼族', '哈萨克族', '傣族', '黎族', '傈僳族', '佤族', '畲族', '高山族', '拉祜族', '水族', '东乡族', '纳西族', '景颇族', '柯尔克孜族', '土族', '达斡尔族', '仫佬族', '羌族', '布朗族', '撒拉族', '毛南族', '仡佬族', '锡伯族', '阿昌族', '普米族', '塔吉克族', '怒族', '乌孜别克族', '俄罗斯族', '鄂温克族', '德昂族', '保安族', '裕固族', '京族', '塔塔尔族', '独龙族', '鄂伦春族', '赫哲族', '门巴族', '珞巴族', '基诺族'
];
onMounted(async () => {
  fetchData();
});
let searchParams = {
  householdNumber: '',
  name: '',
  idNumber: ''
};
const searchWhatis = ref(null);
const input = ref('');
watch(() => {
  if (searchWhatis.value !== null) {
    // 重新获取输入数据
    input.value = '';
    //重置
    searchParams = {}
    console.log("searchParams", searchParams);
  }
});
const search = () => {
  if (searchWhatis.value === '0') {
    searchParams.householdNumber = input.value;
  } else if (searchWhatis.value === '1') {
    searchParams.name = input.value;
  } else if (searchWhatis.value === '2') {
    searchParams.idNumber = input.value;
  }
  fetchData();
};


const tableData = ref([]);
const pagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
});

const fetchData = async () => {
  const { data } = await getPopulationPage({
    currentPage: pagination.currentPage,
    pageSize: pagination.pageSize,
    householdNumber: searchParams.householdNumber,
    name: searchParams.name,
    idNumber: searchParams.idNumber,
  });
  tableData.value = data.data;
  pagination.total = data.total;
  for (let i = 0; i < tableData.value.length; i++) {

  }
};
const confirmDeleteUser = (row) => {
  ElMessageBox.confirm(`确定要删除 ${row.name} 的信息吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteUser(row);
    fetchData();
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

const deleteUser = async (row) => {
  await deletePopulation(row.personId);
  ElMessage.success('删除成功');
  fetchData();
};


const dialogFormVisible = ref(false);
const dialogFormVisibles = ref(false);
const title = ref('添加个人信息');
const populationInfo = reactive({
  personId: '',
  name: '',
  gender: '',
  birthDate: '',
  idNumber: '',
  householdNumber: '',
  relationToHead: '',
  maritalStatus: '',
  educationLevel: '',
  occupation:'',
  phoneNumber: '',
  ethnicity: '',
  isDisabled: '',
  bloodType: '',
  militaryStatus: '',
  household: {
    registeredAddress: ''
  }
});

const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchData();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  fetchData();
};

const openAddUser = async () => {
  dialogFormVisible.value = true;
  title.value = '添加个人信息';
  const { data } = await getPopulationPage({
    currentPage: 1,
    pageSize: 999,
    householdNumber: '',
    name: '',
    idNumber: '',
  });
  if (data.data.length !== 0) {
    const lastPerson = data.data[data.data.length - 1];
    populationInfo.personId = Number(lastPerson.personId) + 1;
  } else {
    populationInfo.personId = 1;
  }
  Object.assign(populationInfo, {
    name: '',
    gender: '',
    birthDate: '',
    idNumber: '',
    householdNumber: '',
    relationToHead: '',
    maritalStatus: '',
    educationLevel: '',
    occupation:'',
    phoneNumber: '',
    ethnicity: '',
    isDisabled: '',
    bloodType: '',
    militaryStatus: '',
    household: {
      registeredAddress: ''
    }
  });
};


const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  birthDate: [{ required: true, message: '请选择出生日期', trigger: 'blur' }],
  idNumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^\d{18}$/, message: '身份证号格式不正确', trigger: 'blur' },
  ],
  ethnicity: [{ required: true, message: '请选择民族', trigger: 'blur' }],
  maritalStatus: [{ required: true, message: '请选择婚姻状况', trigger: 'blur' }],
  educationLevel: [{ required: true, message: '请选择教育程度', trigger: 'blur' }],
  occupation: [{ required: true, message: '请输入职业', trigger: 'blur' }],
  isDisabled: [{ required: true, message: '请选择是否残疾', trigger: 'blur' }],
  bloodType: [{ required: true, message: '请选择血型', trigger: 'blur' }],
  militaryStatus: [{ required: true, message: '请选择服兵役状况', trigger: 'blur' }],

};
//表单验证
const populationInfoForm = ref()

const saveOrUpdatePopulationInfo = async () => {
  const formset = await populationInfoForm.value.validate();
  if (formset) {
    if (title.value === '添加个人信息') {
      const response = await addPopulation(populationInfo);
      if (response.data.state === 1) {
        ElMessage.error('添加失败，身份信息错误');
      } else {
        ElMessage.success('添加成功');
        dialogFormVisible.value = false;
        fetchData();
      }
    } else {
      ElMessage.success('更新成功');
      // 更新个人信息信息逻辑
      await updatePopulation(populationInfo);
      dialogFormVisible.value = false;
      fetchData();
    }
  }
};

// let registeredAddress = ref('');
// const getHousehold = async (row) => {
//   const { data } = await getHouseholdPage({
//     currentPage: pagination.currentPage,
//     pageSize: pagination.pageSize,
//     householdNumber: row.householdNumber,
//   })
//   registeredAddress = data.data[0].registeredAddress;
//   console.log(registeredAddress);
// };

const getUser = async (row) => {
  // if (row.householdNumber) {
  //   await getHousehold(row);
  // }
  // console.log(registeredAddress);
  dialogFormVisibles.value = true;
  title.value = '查看个人信息';
  Object.assign(populationInfo, row);
  fetchData();
};
const editUser = async (row) => {
  // if (row.householdNumber) {
  //   await getHousehold(row);
  // }
  dialogFormVisible.value = true;
  title.value = '编辑个人信息';
  Object.assign(populationInfo, row);
  // populationInfo.registeredAddress = registeredAddress;
  fetchData();
};
const genderFormatter = (cellValue) => {
  if (cellValue === '1') {
    populationInfo.maritalStatus = '男';
    return '男';
  } else {
    populationInfo.maritalStatus = '女';
    return '女';
  }
};

const maritalStatusFormatter = (cellValue) => {
  if (cellValue === '1') {
    populationInfo.maritalStatus = '未婚';
    return '未婚';
  } else if (cellValue === '2') {
    populationInfo.maritalStatus = '已婚';
    return '已婚';
  } else if (cellValue === '3') {
    populationInfo.maritalStatus = '离异';
    return '离异';
  } else {
    populationInfo.maritalStatus = '丧偶';
    return '丧偶';
  }
};

const educationLevelFormatter = (cellValue) => {
  if (cellValue === '1') {
    populationInfo.educationLevel = '学龄前';
    return '学龄前';
  } else if (cellValue === '2') {
    populationInfo.educationLevel = '小学';
    return '小学';
  } else if (cellValue === '3') {
    populationInfo.educationLevel = '初中';
    return '初中';
  } else if (cellValue === '4') {
    populationInfo.educationLevel = '高中';
    return '高中';
  } else if (cellValue === '5') {
    populationInfo.educationLevel = '本科';
    return '本科';
  } else if (cellValue === '6') {
    populationInfo.educationLevel = '研究生';
    return '研究生';
  } else {
    populationInfo.educationLevel = '其他';
    return '其他';
  }
};

const relationToHeadFormatter = (cellValue) => {
  if (cellValue === '1') {
    populationInfo.relationToHead = '配偶';
    return '配偶';
  } else if (cellValue === '2') {
    populationInfo.relationToHead = '子女';
    return '子女';
  } else if (cellValue === '3') {
    populationInfo.relationToHead = '户主';
    return '户主';
  } else if (cellValue === '4') {
    populationInfo.relationToHead = '父母';
    return '父母';
  } else {
    populationInfo.relationToHead = '其他';
    return '其他';
  }
};
</script>

<style scoped>
.el-select {
  width: 160px;
}

.el-pagination {
  margin-top: 20px;
}
</style>